<template>
  <div class="app-container">
    <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
      <a-form-item label="赛事名称" name="name">
        <a-input
            v-model:value="queryParams.name"
            placeholder="请输入赛事名称"
            allow-clear
            @pressEnter="handleQuery"
        />
      </a-form-item>
      <a-form-item label="参赛车辆" name="cansaicheliang">
        <a-input
            v-model:value="queryParams.cansaicheliang"
            placeholder="请输入参赛车辆"
            allow-clear
            @pressEnter="handleQuery"
        />
      </a-form-item>

      <a-form-item label="赛事地址" name="saishidizhi">
        <a-input
            v-model:value="queryParams.saishidizhi"
            placeholder="请输入赛事地址"
            allow-clear
            @pressEnter="handleQuery"
        />
      </a-form-item>
      <a-form-item label="开始时间" name="starttime">
        <a-date-picker
                        v-model:value="queryParams.starttime"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择开始时间">
        </a-date-picker>
      </a-form-item>
      <a-form-item label="结束时间" name="endtime">
        <a-date-picker
                        v-model:value="queryParams.endtime"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择结束时间">
        </a-date-picker>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="resetQuery" style="margin-left: 8px">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button
            type="primary"
            @click="handleAdd"
            v-privilege="['eventSys:eventInfo:add']"
        >
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
            type="default"
            :disabled="single"
            @click="handleUpdate"
            v-privilege="['eventSys:eventInfo:edit']"
        >
          <template #icon><EditOutlined /></template>
          修改
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
            type="primary"
            danger
            :disabled="multiple"
            @click="handleDelete"
            v-privilege="['eventSys:eventInfo:remove']"
        >
          <template #icon><DeleteOutlined /></template>
          删除
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
            type="default"
            @click="handleExport"
            v-privilege="['eventSys:eventInfo:export']"
        >
          <template #icon><DownloadOutlined /></template>
          导出
        </a-button>
      </a-col>
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </a-row>

    <a-table :loading="loading" :data-source="eventInfoList" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }" row-key="id">
      <a-table-column title="赛事名称" data-index="name" align="center"/>
      <a-table-column title="赛事介绍" data-index="description" align="center">
        <template #default="{ record }">
          <div class="description-container">
            <span class="preview-text">{{ truncateText(record.description) }}</span>
            <a-button
                v-if="showMoreButton(record.description)"
                type="link"
                @click="openContentDialog(record.description)"
            >
              查看
            </a-button>
          </div>
        </template>
      </a-table-column>

      <!-- 在文件末尾添加内容对话框 -->
      <a-modal
          v-model:open="contentDialogVisible"
          title="完整内容"
          width="60%"
          :after-close="() => { currentContent = ''; }"
      >
        <div class="full-content">{{ currentContent }}</div>
        <template #footer>
          <a-button @click="contentDialogVisible = false">关闭</a-button>
        </template>
      </a-modal>
      <a-table-column title="赛事图片" data-index="image" align="center" :width="100">
        <template #default="{ record }">
          <image-preview :src="record.image" :width="50" :height="50"/>
        </template>
      </a-table-column>
      <a-table-column title="赛事状态" data-index="status" align="center"/>
      <a-table-column title="参赛车辆" data-index="cansaicheliang" align="center"/>
      <a-table-column title="车辆数量" data-index="cheliangshuliang" align="center"/>
      <a-table-column title="赛事位置" data-index="saishiweizhi" align="center"/>
      <a-table-column title="赛事地址" data-index="saishidizhi" align="center"/>
      <a-table-column title="开始时间" data-index="starttime" align="center" :width="180">
        <template #default="{ record }">
          <span>{{ parseTime(record.starttime, '{y}-{m}-{d}') }}</span>
        </template>
      </a-table-column>
      <a-table-column title="结束时间" data-index="endtime" align="center" :width="180">
        <template #default="{ record }">
          <span>{{ parseTime(record.endtime, '{y}-{m}-{d}') }}</span>
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleUpdate(record)"
                     v-privilege="['eventSys:eventInfo:edit']">
              <template #icon><EditOutlined /></template>
              修改
            </a-button>
            <a-button type="link" danger @click="handleDelete(record)"
                     v-privilege="['eventSys:eventInfo:remove']">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <div class="table-pagination" style="margin-top: 16px; text-align: right" v-show="total > 0">
      <a-pagination
          :total="total"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          @change="handlePageChange"
          @showSizeChange="handlePageSizeChange"
          show-size-changer
          :show-total="(total) => `共 ${total} 条`"
      />
    </div>

    <!-- 添加或修改赛事信息对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px">
      <a-form ref="eventInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="赛事名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入赛事名称"/>
        </a-form-item>
        <a-form-item label="赛事介绍" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入内容"/>
        </a-form-item>
        <a-form-item label="赛事图片" name="image">
          <image-upload v-model:value="form.image"/>
        </a-form-item>
        <a-form-item label="参赛车辆" name="cansaicheliang">
          <a-input v-model:value="form.cansaicheliang" placeholder="请输入参赛车辆"/>
        </a-form-item>
        <a-form-item label="车辆数量" name="cheliangshuliang">
          <a-input v-model:value="form.cheliangshuliang" placeholder="请输入车辆数量"/>
        </a-form-item>
        <a-form-item label="赛事位置" name="saishiweizhi">
          <a-input
              v-model:value="form.saishiweizhi"
              placeholder="请选择赛事位置"
              readonly
          />
          <a-button type="primary" @click="openMapDialog" style="margin-top: 8px">选取位置</a-button>
        </a-form-item>
        <a-form-item label="赛事地址" name="saishidizhi">
          <a-input v-model:value="form.saishidizhi" placeholder="请输入赛事地址"/>
        </a-form-item>
        <a-form-item label="开始时间" name="starttime">
          <a-date-picker
                          v-model:value="form.starttime"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开始时间">
          </a-date-picker>
        </a-form-item>
        <a-form-item label="结束时间" name="endtime">
          <a-date-picker
                          v-model:value="form.endtime"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结束时间">
          </a-date-picker>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" @click="submitForm">确 定</a-button>
        <a-button @click="cancel">取 消</a-button>
      </template>
    </a-modal>
    <!-- 地图选点对话框 -->
    <a-modal title="地图选点" v-model:open="mapDialogVisible" width="70%" :after-close="closeMapDialog">
      <div id="mapContainer" class="map-container"></div>
      <template #footer>
        <a-button @click="closeMapDialog">取消</a-button>
        <a-button type="primary" @click="confirmLocation">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="EventInfo">
import {
  listEventInfo,
  getEventInfo,
  delEventInfo,
  addEventInfo,
  updateEventInfo
} from "/@/api/offroad/eventSys/eventInfo";
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { 
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';

const parseTime = (time, format) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return format.replace('{y}', year).replace('{m}', month).replace('{d}', day);
};

const { proxy } = getCurrentInstance();

const eventInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const mapDialogVisible = ref(false);
const selectedRowKeys = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    description: null,
    image: null,
    status: null,
    cansaicheliang: null,
    cheliangshuliang: null,
    saishiweizhi: null,
    saishidizhi: null,
    starttime: null,
    endtime: null
  },
  rules: {
    name: [
      { required: true, message: "赛事名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

let map = null;
let marker = null;
let pickedLngLat = null;
let pickedAddress = '';

function openMapDialog() {
  mapDialogVisible.value = true;
  nextTick(() => {
    if (!map) initMap();
  });
}

function closeMapDialog() {
  mapDialogVisible.value = false;
}

async function initMap() {
  await AMapLoader.load({key: 'b16861868f00acd6d2cb883e30e5b598', version: '2.0', plugins: ['AMap.Geocoder']});
  map = new AMap.Map('mapContainer', {zoom: 15, center: [116.397428, 39.90923]});
  const geocoder = new AMap.Geocoder();
  map.on('click', async e => {
    const {lng, lat} = e.lnglat;
    pickedLngLat = [lng, lat];
    if (marker) marker.setPosition([lng, lat]);
    else marker = new AMap.Marker({position: [lng, lat], map});
    const res = await geocoder.getAddress([lng, lat]);
    pickedAddress = res.regeocode.formattedAddress;
  });
}

function confirmLocation() {
  if (pickedLngLat) {
    form.value.saishiweizhi = `${pickedLngLat[1].toFixed(6)},${pickedLngLat[0].toFixed(6)}`;
    form.value.saishidizhi = pickedAddress;
  }
  closeMapDialog();
}

function cancel() {
  open.value = false;
}

// 在script部分添加
const contentDialogVisible = ref(false);
const currentContent = ref('');

// 文本截断方法
const truncateText = (text) => {
  if (!text) return '';
  return text.length > 20 ? text.slice(0, 20) + '...' : text;
};

// 判断是否需要显示"查看"按钮
const showMoreButton = (text) => {
  return text && text.length > 20;
};

// 打开内容对话框
const openContentDialog = (content) => {
  currentContent.value = content || '';
  contentDialogVisible.value = true;
};


/** 查询赛事信息列表 */
function getList() {
  loading.value = true;
  listEventInfo(queryParams.value).then(response => {
    eventInfoList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    description: null,
    image: null,
    status: null,
    cansaicheliang: null,
    cheliangshuliang: null,
    saishiweizhi: null,
    saishidizhi: null,
    starttime: null,
    endtime: null
  };
  proxy.resetForm("eventInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedKeys, selectedRows) {
  selectedRowKeys.value = selectedKeys;
  ids.value = selectedRows.map(item => item.id);
  single.value = selectedRows.length != 1;
  multiple.value = !selectedRows.length;
}

// 分页页码变化
function handlePageChange(page, pageSize) {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = pageSize;
  getList();
}

// 分页大小变化
function handlePageSizeChange(current, size) {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = size;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加赛事信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getEventInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改赛事信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["eventInfoRef"].validate().then(() => {
    if (form.value.id != null) {
      updateEventInfo(form.value).then(response => {
        proxy.$message.success("修改成功");
        open.value = false;
        getList();
      });
    } else {
      addEventInfo(form.value).then(response => {
        proxy.$message.success("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm({
    title: '确认删除',
    content: '是否确认删除赛事信息编号为"' + _ids + '"的数据项？',
    onOk() {
      return delEventInfo(_ids).then(() => {
        getList();
        proxy.$message.success("删除成功");
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('eventSys/eventInfo/export', {
    ...queryParams.value
  }, `eventInfo_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
/* 添加样式 */
.description-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.full-content {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 16px;
  line-height: 1.6;
}
</style>

<style scoped>
.map-container {
  width: 100%;
  height: 400px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.mb8 {
  margin-bottom: 8px;
}

.small-padding {
  padding: 4px;
}

.fixed-width {
  width: 120px;
}

.dialog-footer {
  text-align: right;
}

.table-pagination {
  margin-top: 16px;
  text-align: right;
}
</style>